<template>
  <div class="container" style="padding-bottom: 100px">
    <div style="margin-bottom: 20px">
      <el-input
        style="width: 240px; margin-right: 20px"
        placeholder="请输入剧名"
        v-model="name"
      ></el-input>
      <el-button style="margin-left: 5px" type="primary" @click="loadFilePage"
        ><i class="el-icon-search"></i> 搜索</el-button
      >
      <el-button style="margin-left: 5px" type="warning" @click="reset"
        ><i class="el-icon-refresh"></i> 重置</el-button
      >
    </div>

    <div class="operation-row">
      <div class="left-buttons">
        <el-button
          type="primary"
          @click="handleAdd"
          ><i class="el-icon-plus"></i> 新增</el-button
        >
        <el-popconfirm
          class="ml-5"
          confirm-button-text="确定"
          cancel-button-text="我再想想"
          icon="el-icon-info"
          icon-color="red"
          title="您确定批量删除这些数据吗？"
          @confirm="delBatch"
        >
          <template v-slot:reference>
            <el-button type="danger"
              >批量删除 <i class="el-icon-remove-outline"></i
            ></el-button>
          </template>
        </el-popconfirm>
      </div>
    </div>

    <div class="category-filter">
      <el-radio-group v-model="contentType" @change="handleTypeChange">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="电影">电影</el-radio-button>
        <el-radio-button label="电视剧">电视剧</el-radio-button>
        <el-radio-button label="动漫">动漫</el-radio-button>
        <el-radio-button label="综艺">综艺</el-radio-button>
        <el-radio-button label="短剧">短剧</el-radio-button>
      </el-radio-group>
    </div>

    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="detailsId" label="编号" width="100"></el-table-column>
      <el-table-column prop="name" label="剧名" width="120"></el-table-column>
      <el-table-column prop="actors" label="主演" width="100">
        <template v-slot="{ row }">
          <span>{{ truncateString(row.actors,20)}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="cover" label="封面" width="150px">
        <template v-slot="scope">
          <el-image 
            style="width: 120px; height: 120px"
            :src="scope.row.cover"
            :preview-src-list="[scope.row.cover]"
            fit="cover"
            :initial-index="0"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" width="300px">
        <template v-slot="{ row }">
          <span>{{ truncateString(row.description, 20) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="classify" label="分类" width="150px"></el-table-column>
      <el-table-column prop="quantity" label="点赞数"></el-table-column>
      <el-table-column prop="collect" label="收藏数"></el-table-column>
      <el-table-column label="操作" width="350">
        <template v-slot="scope">
          <el-button type="success" @click="showEpisodes(scope.row)">查看剧集</el-button>
          <el-button type="primary" @click="handEdit(scope.row)">编辑</el-button>
          <el-popconfirm
            style="margin-left: 5px"
            title="您确定删除这行数据吗？"
            @confirm="del(scope.row.detailsId)"
          >
            <template v-slot:reference><el-button type="danger">删除</el-button></template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="信息"
      v-model="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <el-form label-width="120px" style="width: 80%; margin: 0 auto">
        <el-form-item label="剧名" prop="username">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="classify">
          <el-input v-model="form.classify" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            style="width: 300px"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="点赞数" prop="quantity">
          <el-input v-model="form.quantity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="收藏数" prop="collect">
          <el-input v-model="form.collect" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="主演" prop="actors">
          <el-input 
            v-model="form.actors" 
            style = "width: 300px" :autosize="{ minRows: 2, maxRows: 4 }" 
            type="textarea" 
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="cover" label="封面图片">
          <el-upload
            action="http://localhost:9090/api/file/cover"
            ref="coverUpload"
            :data="getUploadData"
            :before-upload="beforeCoverUpload"
            @success="handleImgUploadSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-pagination
      style="justify-content: center; margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[2, 5, 10, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加剧集列表对话框 -->
    <el-dialog
      title="剧集列表"
      v-model="episodesDialogVisible"
      width="70%"
      :destroy-on-close="true"
      @close="handleDialogClose"
    >
      <div style="margin-bottom: 20px">
        <el-button type="primary" @click="handleAddEpisode">添加剧集</el-button>
      </div>
      
      <el-table :data="episodesList" style="width: 100%">
        <el-table-column prop="diversity" label="集数" width="80"></el-table-column>
        <el-table-column prop="name" label="标题" width="200"></el-table-column>
        <el-table-column prop="url" label="视频链接"></el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="scope">
            <el-button type="primary" @click="editEpisode(scope.row)">编辑</el-button>
            <!-- <el-button type="danger" @click="deleteEpisode(scope.row)">删除</el-button> -->
            <el-popconfirm
            style="margin-left: 5px"
            title="您确定删除这行数据吗？"
            @confirm="deleteEpisode(scope.row)"
          >
            <template v-slot:reference><el-button type="danger">删除</el-button></template>
          </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加/编辑剧集的对话框 -->
    <el-dialog
      :title="episodeForm.episodeId ? '编辑剧集' : '添加剧集'"
      v-model="episodeFormVisible"
      width="40%"
    >
      <el-form :model="episodeForm" label-width="100px">
        <el-form-item label="集数">
          <el-input v-model="episodeForm.diversity" type="number"></el-input>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="episodeForm.name"></el-input>
        </el-form-item>
        <el-form-item label="视频链接">
          <el-input v-model="episodeForm.url"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="episodeFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEpisode">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick } from "vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
// import axios from "axios";
import { useRouter } from "vue-router";
const router=useRouter()
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(5);
const dialogVisible = ref(false);
const tableData = ref([]);
const multipleSelection = ref([]);
const classify = ref("");
const NewCover=ref("");
const NewName=ref("")
const name=ref('');
const coverUpload = ref(null)
const form = ref({
  name: "",
  classify: "",
  description: "",
  actors: "",
  cover: "",
  quantity: "",
  collect: ""
});
const episodesDialogVisible = ref(false)
const episodeFormVisible = ref(false)
const episodesList = ref([])
const currentDetailsId = ref(null)
const episodeForm = ref({
  episodeId: null,
  detailsId: null,
  diversity: '',
  name: '',
  url: ''
})
const contentType = ref('all')

onMounted(() => {
  loadFilePage();
});
const getUploadData = () => {
  console.log(NewName.value,"====");
  return {
    name: NewName.value, // Dynamic value of name
  };

};

//字数限制
const truncateString = (str, maxLength) => {
  if (!str) return "";
  if (str.length <= maxLength) {
    return str;
  } else {
    return str.slice(0, maxLength) + "...";
  }
};

const save = async () => {
  console.log(form.value)
  const res = await request.post("/details/save", form.value);
  console.log(form.value)
  if (res.data.code === "200") {
    ElMessage.success("添加成功");
    dialogVisible.value = false;
    loadFilePage();
  } else {
    ElMessage.error("添加失败");
  }
};

const beforeCoverUpload = async () => {
  // 在上传新图片之前，先删除原有图片
  await deleteOldImage(); // 调用删除原有图片的方法
  // 继续上传新图片
  return true;
};

const deleteOldImage = async () => {
  try {
    // 假设你从后端获取了原有图片的URL
    const cover =NewCover.value
    console.log(cover,"===");
    // 发送请求删除原有图片
    await request.post('/file/coverOne', { params: { cover: cover } });
    console.log("原有图片删除成功");
 
  } catch (error) {
    console.error("原有图片删除失败", error);
  }
};
const handleImgUploadSuccess = (response) => {
  form.value.cover = response;
  console.log("img--",response);
};

const del = async (detailsId) => {
  const res = await request.delete(`/details/${detailsId}`);
  if (res.data.code === "200") {
    ElMessage.success("删除成功");
    loadFilePage();
  } else {
    ElMessage.error("删除失败");
  }
};

const reset = () => {
  name.value = '';
  classify.value = '';
  contentType.value = 'all';
  loadFilePage();
};

const resetForm = () => {
  form.value = {
    name: "",
    classify: "",
    description: "",
    actors: "",
    cover: "",
    quantity: "",
    collect: ""
  }
  NewCover.value = ''
  NewName.value = ''
  // 清除上传组件的状态
  if (coverUpload.value) {
    coverUpload.value.clearFiles()
  }
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const loadFilePage = async () => {
  try {
    const res = await request.get("/details/pagingList", {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        name: name.value,
        classify: classify.value,
        type: contentType.value === 'all' ? '' : contentType.value
      },
    });
    console.log('---',res);
    
    tableData.value = res.data.data.records || [];
    total.value = res.data.data.total || 0;
  } catch (error) {
    if (error.response) {
    // 请求已发出，但服务器响应了状态码不在2xx范围内的内容
    console.error('服务器响应错误:', error.response.status, error.response.data);
    // 你可以根据状态码做不同的处理
    if (error.response.status === 402 || error.response.status === 405) {
      // 处理405错误
    localStorage.removeItem('token')
    localStorage.removeItem('userName')
    localStorage.removeItem('menus')
    localStorage.removeItem('userType')
    // 重定向到登录页面
    router.push('/login')
    }
  } else if (error.request) {
    // 请求已发出，但没有收到响应
    console.error('请求已发送，但未收到响应:', error.request);
  } else {
    // 其他错误（如配置错误导致请求未发送）
    console.error('错误:', error.message);
  }
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  loadFilePage();
};

const handleCurrentChange = (val) => {
  pageNum.value = val;
  loadFilePage();
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const delBatch = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.error("请选择需要删除的数据");
    return;
  }

  const ids = multipleSelection.value.map((v) => v.detailsId);
  try {
    const res = await request.post("/details/del/batch", ids);
    if (res.data.code === "200") {
      ElMessage.success("批量删除成功");
      loadFilePage();
    } else {
      ElMessage.error("批量删除失败");
    }
  } catch (error) {
    console.error("批量删除错误:", error);
    ElMessage.error("批量删除失败，请重试");
  }
};

const handEdit = (row) => {
  form.value = { ...row };
  NewCover.value=form.value.cover
  NewName.value=form.value.name
  console.log("====",form.value);
  dialogVisible.value = true;
};

const showEpisodes = async (row) => {
  currentDetailsId.value = row.detailsId
  try {
    const res = await request.get(`/episodes/list/${row.detailsId}`)
    if (res.data.code === '200') {
      episodesList.value = res.data.data
      episodesDialogVisible.value = true
      await nextTick()
    }
  } catch (error) {
    ElMessage.error('获取剧集列表失败')
  }
}

const handleAddEpisode = () => {
  episodeForm.value = {
    episodeId: null,
    detailsId: currentDetailsId.value,
    diversity: '',
    name: '',
    url: ''
  }
  episodeFormVisible.value = true
}

const editEpisode = (row) => {
  episodeForm.value = {
    episodeId: row.episodeId,
    detailsId: currentDetailsId.value,
    diversity: row.diversity,
    name: row.name,
    url: row.url
  }
  episodeFormVisible.value = true
}

const saveEpisode = async () => {
  try {
    const url = episodeForm.value.episodeId ? '/files/update' : '/files/save'
    const res = await request.post(url, episodeForm.value)
    if (res.data.code === '200') {
      ElMessage.success(episodeForm.value.episodeId ? '更新成功' : '添加成功')
      episodeFormVisible.value = false
      showEpisodes({ detailsId: currentDetailsId.value }) // 刷新剧集列表
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const deleteEpisode = async (row) => {
  try {
    const res = await request.delete(`/file/${row.episodeId}`)
    if (res.data.code === '200') {
      ElMessage.success('删除成功')
      showEpisodes({ detailsId: currentDetailsId.value }) // 刷新剧集列表
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const handleDialogClose = () => {
  episodesDialogVisible.value = false
  episodesList.value = []
}

const handleTypeChange = () => {
  pageNum.value = 1
  loadFilePage()
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.operation-row {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 10px 0 20px 0;
  padding: 10px 0;
}

.left-buttons {
  display: flex;
  gap: 10px;
}

.category-filter {
  margin: 25px 0;
}

.category-filter .el-radio-group {
  display: flex;
  gap: 20px;
}

.category-filter .el-radio-button__inner {
  padding: 20px 60px;
  font-size: 20px;
  font-weight: 600;
  height: auto;
  line-height: 1.5;
  min-width: 120px;
  text-align: center;
}

.category-filter .el-radio-button__original-radio:checked + .el-radio-button__inner {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
  font-weight: bold;
}

.category-filter .el-radio-button:first-child .el-radio-button__inner {
  border-radius: 4px;
}

.category-filter .el-radio-button:last-child .el-radio-button__inner {
  border-radius: 4px;
}

.filter-section {
  display: none;
}
</style>
